<template>
	<div class="head-image" @click="showUserInfo($event)" :style="{ cursor: isShowUserInfo ? 'pointer' : null }">
		<!-- 头像图片 -->
		<img class="avatar-image" v-show="displayUrl && !imageError" :src="displayUrl" :style="avatarImageStyle"
			@load="onImageLoad" @error="onImageError" loading="eager" />
		<!-- 加载状态 -->
		<div class="avatar-loading" v-show="isLoading && !displayUrl" :style="avatarTextStyle">
			<i class="el-icon-loading"></i>
		</div>
		<!-- 默认头像文字 -->
		<div class="avatar-text" v-show="(!displayUrl || imageError) && !isLoading" :style="avatarTextStyle">
			{{ name?.substring(0, 2).toUpperCase() }}
		</div>
		<!-- 在线状态 -->
		<div v-show="online" class="online" title="用户当前在线"></div>
		<slot></slot>
	</div>
</template>

<script>
import { findUserByIdApi } from '@/api/imUser.js'
import avatarCache from '@/utils/im/avatarCache.js'

export default {
	name: "headImage",
	data() {
		return {
			colors: ["#5daa31", "#c7515a", "#e03697", "#85029b",
				"#c9b455", "#326eb6"],
			displayUrl: '', // 实际显示的头像URL
			imageError: false, // 图片加载错误状态
			isLoading: false, // 加载状态
			loadTimeout: null // 加载超时定时器
		}
	},
	props: {
		id: {
			type: Number
		},
		size: {
			type: Number,
			default: 42
		},
		width: {
			type: Number
		},
		height: {
			type: Number
		},
		radius: {
			type: String,
			default: "50%"
		},
		url: {
			type: String
		},
		name: {
			type: String,
			default: null
		},
		online: {
			type: Boolean,
			default: false
		},
		isShowUserInfo: {
			type: Boolean,
			default: true
		},
		// 新增：头像类型，用于区分用户头像和群聊头像
		type: {
			type: String,
			default: 'user', // 'user' 或 'group'
			validator: value => ['user', 'group'].includes(value)
		}
	},
	mounted() {
		this.loadAvatar();
	},
	watch: {
		url: {
			handler() {
				this.loadAvatar();
			},
			immediate: false
		},
		id: {
			handler(newId) {
				if (newId && !this.url) {
					this.loadAvatarFromCache();
				}
			},
			immediate: false
		},
		type: {
			handler() {
				// 当type变化时，重新加载头像
				if (this.id && !this.url) {
					this.loadAvatarFromCache();
				}
			},
			immediate: false
		}
	},
	methods: {
		/**
		 * 加载头像
		 */
		async loadAvatar() {
			// 清除之前的超时定时器
			if (this.loadTimeout) {
				clearTimeout(this.loadTimeout);
				this.loadTimeout = null;
			}

			// 重置状态
			this.imageError = false;

			// 如果有URL，直接使用
			if (this.url) {
				this.displayUrl = this.url;
				// 预加载头像到缓存，只有当URL存在时才缓存
				if (this.id && this.url.trim()) {
					avatarCache.setAvatar(this.id, this.url, this.type);
				}
				// 预加载图片
				this.preloadImage(this.url);
				return;
			}

			// 如果没有URL但有ID，尝试从缓存获取
			if (this.id) {
				this.loadAvatarFromCache();
			}
		},

		/**
		 * 从缓存加载头像
		 */
		loadAvatarFromCache() {
			if (!this.id) return;

			// 重置显示状态
			this.displayUrl = '';
			this.isLoading = false;

			const cachedUrl = avatarCache.getAvatar(this.id, this.type);
			if (cachedUrl && cachedUrl.trim()) {
				// 缓存中有有效的头像URL
				this.displayUrl = cachedUrl;
				this.preloadImage(cachedUrl);
			} else {
				// 缓存中没有真实头像URL
				if (this.type === 'group') {
					// 群聊没有头像时，不显示加载状态，直接显示文字头像
					this.isLoading = false;
				} else {
					// 用户头像缓存中没有，显示加载状态
					this.isLoading = true;
					// 设置超时，避免一直显示加载状态
					this.loadTimeout = setTimeout(() => {
						this.isLoading = false;
					}, 3000);
				}
			}
		},

		/**
		 * 预加载图片
		 */
		preloadImage(url) {
			if (!url) return;

			avatarCache.preloadAvatar(url).catch(() => {
				// 预加载失败，不影响显示
			});
		},

		/**
		 * 图片加载成功
		 */
		onImageLoad() {
			this.imageError = false;
			this.isLoading = false;
			if (this.loadTimeout) {
				clearTimeout(this.loadTimeout);
				this.loadTimeout = null;
			}
		},

		/**
		 * 图片加载失败
		 */
		onImageError() {
			this.imageError = true;
			this.isLoading = false;
			if (this.loadTimeout) {
				clearTimeout(this.loadTimeout);
				this.loadTimeout = null;
			}
		},

		showUserInfo(e) {
			if (!this.isShowUserInfo) return;
			if (this.id && this.id > 0) {
				findUserByIdApi(this.id).then((res) => {
					let pos = {
						x: e.x + 30,
						y: e.y
					}
					this.$eventBus.$emit("openUserInfo", res.data, pos);
				}).catch((error) => {
					console.error("获取用户信息失败：", error);
				})
			}
		}
	},
	beforeDestroy() {
		// 清理定时器
		if (this.loadTimeout) {
			clearTimeout(this.loadTimeout);
		}
	},
	computed: {
		avatarImageStyle() {
			let w = this.width ? this.width : this.size;
			let h = this.height ? this.height : this.size;
			return `width:${w}px; height:${h}px;
					border-radius: ${this.radius};`
		},
		avatarTextStyle() {
			let w = this.width ? this.width : this.size;
			let h = this.height ? this.height : this.size;
			return `
				  width: ${w}px;height:${h}px;
					background-color: ${this.name ? this.textColor : '#fff'};
					font-size:${w * 0.35}px;
					border-radius: ${this.radius};
					`
		},
		textColor() {
			let hash = 0;
			for (var i = 0; i < this.name.length; i++) {
				hash += this.name.charCodeAt(i);
			}
			return this.colors[hash % this.colors.length];
		}
	}
}
</script>

<style scoped lang="scss">
.head-image {
	position: relative;

	.avatar-image {
		position: relative;
		overflow: hidden;
		display: block;
	}

	.avatar-text {
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: 500;
	}

	.avatar-loading {
		display: flex;
		align-items: center;
		justify-content: center;
		background: var(--im-bg-secondary, #f5f5f5);
		color: var(--im-text-color-secondary, #999);

		i {
			font-size: 16px;
			animation: rotate 1s linear infinite;
		}
	}

	.online {
		position: absolute;
		right: -5px;
		bottom: 0;
		width: 12px;
		height: 12px;
		background: limegreen;
		border-radius: 50%;
		border: 2px solid white;
	}
}

// 旋转动画
@keyframes rotate {
	from {
		transform: rotate(0deg);
	}

	to {
		transform: rotate(360deg);
	}
}
</style>
